package com.acme.bankapp.service.bank;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.bank.exceptions.BankException;

public class ServerBank {
	public static void main(String[] args) {
		try (ServerSocket serverSocket = new ServerSocket(1234)) {
			try (Socket socket = serverSocket.accept();
					PrintWriter writer = new PrintWriter(
							socket.getOutputStream(), true);
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(socket.getInputStream()));) {
				try {
					String inputClient;
					Bank bank = new Bank();
					while ((inputClient = reader.readLine()) != null) {
						if (inputClient.equals("End communication"))
							break;
						bank.addClient(BankDataLoaderService
								.parseFeedLine(inputClient));
					}
					System.out.println("Data loaded");
					writer.println("Data loaded:");
					writer.println(bank.getClients().size() + " clients");
					System.out.println("conformation send");
				} catch (BankException e) {
					writer.println("Wrong data");
					e.printStackTrace();
				}
			}
		} catch (IOException e) {
			System.out.println("Connection problem");
			e.printStackTrace();
		}
	}
}
